package com.lr.controller;

import com.deepoove.poi.data.PictureRenderData;
import com.lr.entity.Company;
import com.lr.entity.JobFair;
import com.lr.entity.Recruit;
import com.lr.entity.Resume;
import com.lr.service.DWService;
import com.lr.util.FileUtilsDelete;
import com.lr.util.VerifyCodeUtil;
import com.lr.util.WordUtil;
import com.lr.util.ZipUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipOutputStream;

@RestController
public class DWController {
    @Value("${VDirPath}")
    private String VDirPath;
    @Value("${VPath}")
    private String vPath;
    @Value("${ResumeName}")
    private String ResumeName;
    @Autowired
    private DWService dwService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/dwRegister")
    public Integer  Register(@RequestParam(value = "userName")String userName, @RequestParam(value = "password")String password){
        return dwService.Register(userName,password);
    }
    @RequestMapping("/dwCreateCode")
    public void grCreateCode(HttpServletResponse resp, HttpSession session) throws Exception {
        OutputStream out=resp.getOutputStream();
        String code= VerifyCodeUtil.generateVerifyCode(4);
        //session.setAttribute("grcode", code);  //存入session中
        //redisTemplate.opsForValue().set(session.getId()+"grcode",code,60, TimeUnit.SECONDS);  redis中
        redisTemplate.opsForValue().set(session.getId()+"dwcode",code);  //redis中
        VerifyCodeUtil.outputImage(86, 30, out, code);
        out.close();
    }
    @RequestMapping(value = "/dwLogin",method={RequestMethod.POST})
    public String  login(@RequestParam(value = "userName")String userName,@RequestParam(value = "password")String password,@RequestParam(value = "code")String code,HttpSession session){
        return dwService.login(userName,password,code,session);
    }
    @RequestMapping(value = "/dw/dwInfo.action",method={RequestMethod.POST})
    public Company dwInfo(ServletRequest request){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.dwInfo(userJSON);
    }
    @RequestMapping(value = "/dw/dwVerifyPassword.action",method={RequestMethod.POST})
    public Integer dwVerifyPassword(ServletRequest request,String password){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.dwVerifyPassword(userJSON,password);
    }
    @RequestMapping("/dw/uploadLogo.action")
    public String uploadLogo(MultipartFile file) throws IllegalAccessException, IOException {
        File f=new File(VDirPath);
        if(!f.exists()){
            f.mkdirs();
        }
        String headImage= UUID.randomUUID().toString()+".jpg";
        file.transferTo(new File(f,headImage));
        return vPath+File.separator+headImage;
    }
    @RequestMapping(value = "/dw/updateCompany.action",method={RequestMethod.POST})
    public Integer updateCompany(ServletRequest request,Company company){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.updateCompany(userJSON,company);
    }
    @RequestMapping(value = "/dw/searchResume.action",method={RequestMethod.POST})
    public List<Resume> searchResume(@RequestParam(value = "name")String name, @RequestParam(value = "major")String major, @RequestParam(value = "whcd")String whcd, @RequestParam(value = "gznx")String gznx, @RequestParam(value = "zzmm")String zzmm, @RequestParam(value = "phone")String phone){
        Resume resume=new Resume();
        resume.setName(name);
        resume.setMajor(major);
        resume.setWhcd(whcd);
        resume.setZzmm(zzmm);
        resume.setPhone(phone);
        resume.setGznx(gznx);
        return dwService.searchResume(resume);
    }
    @RequestMapping(value = "/dw/getResumeById.action",method={RequestMethod.POST})
    public Resume getResumeById(ServletRequest request,Integer resumeId){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.getResumeById(userJSON,resumeId);
    }
    @RequestMapping(value = "/dw/getRecruit.action",method={RequestMethod.POST})
    public Map getRecruit(ServletRequest request){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.getRecruit(userJSON);
    }
    @RequestMapping(value = "/dw/addRecruit.action",method={RequestMethod.POST})
    public Integer addRecruit(Recruit recruit){
        return dwService.addRecruit(recruit);
    }

    @RequestMapping(value = "/dw/updateRecruitStatus.action",method={RequestMethod.POST})
    public Integer updateRecruitStatus(@RequestParam(value = "id")Integer id,@RequestParam(value = "status")Integer status){
        return dwService.updateRecruitStatus(id,status);
    }
    @RequestMapping(value = "/dw/delRecruit.action",method={RequestMethod.POST})
    public Integer delRecruit(Integer id){
        return dwService.delRecruit(id);
    }
    @RequestMapping(value = "/dw/getRecruitById.action",method={RequestMethod.POST})
    public Recruit getRecruitById(Integer id){
        return dwService.getRecruitById(id);
    }
    @RequestMapping(value = "/dw/upRecruitById.action",method={RequestMethod.POST})
    public Integer upRecruitById(Recruit recruit){
        return dwService.upRecruitById(recruit);
    }    @RequestMapping(value = "/dw/getQZInfo.action",method={RequestMethod.POST})
    public List<Recruit> getQZInfo(ServletRequest request,Recruit recruit){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.getQZInfo(userJSON);
    }
    @RequestMapping("/dw/downloadResumeZip.action")
    public void downloadResumeZip(HttpServletResponse response,ServletRequest request) throws IOException {
        HttpServletRequest req=(HttpServletRequest)request;
        Integer recruitId=Integer.parseInt(req.getHeader("id"));
        String gwmc=req.getHeader("gwmc");
        String temp=VDirPath+"/"+new Date().getTime();  //临时目录，存放所有简历的，用时间命名的目的是为了保证多个用户不互相影响
        File file=new File(temp);  //创建临时目录
        if(!file.exists()) {
            file.mkdirs();
        }
        List<Resume> resumeList=dwService.getResumeByRecruitId(recruitId);
        for(Resume resume:resumeList) {
            Map<String,Object> map=new HashMap<String,Object>();
            String sex="";
            if(resume.getSex()==1) {
                sex="男";
            }
            if(resume.getSex()==2) {
                sex="女";
            }
            map.put("sex", sex);
            map.put("name", resume.getName());
            map.put("birthday", resume.getBirthday());
            map.put("natio", resume.getNatio());
            map.put("zzmm", resume.getZzmm());
            map.put("height", resume.getHeight());
            map.put("address", resume.getAddress());
            map.put("phone", resume.getPhone());
            map.put("email", resume.getEmail());
            map.put("whcd", resume.getWhcd());
            map.put("educateTime", resume.getEducateTime());
            map.put("school", resume.getSchool());
            map.put("major", resume.getMajor());
            map.put("course", resume.getCourse());
            map.put("jobExper", resume.getJobExper());
            map.put("schoolExper", resume.getSchoolExper());
            map.put("skill", resume.getSkill());
            map.put("self", resume.getSelf());
            map.put("gznx", resume.getGznx());
            //读取图片
            if(resume.getHeadImage()!=null && !"".equals(resume.getHeadImage())){
                map.put("headImage", new PictureRenderData(180, 180,VDirPath+File.separator+resume.getHeadImage().substring(vPath.length()) ));
            }

            //生成简历word，放入临时目录中
            WordUtil.createWord(response,map,VDirPath+File.separator+ResumeName,resume.getName()+".docx",temp);
        }

        //把临时目录压缩为.zip包，进行下载，压缩包的名字以岗位名称命名
        String zipName = gwmc+".zip";
        response.setContentType("application/zip;charset=utf-8");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {
            ZipUtils.doCompress(temp, out);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            out.close();
        }
        //最后删除服务器产生的临时目录
        FileUtilsDelete.delete(temp);
    }
    @RequestMapping(value = "/dw/getJobFair.action",method={RequestMethod.POST})
    public List<JobFair> getJobFair(ServletRequest request){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.getJobFair(userJSON);
    }
    @RequestMapping(value = "/dw/addJobFair.action",method={RequestMethod.POST})
    public Integer addJobFair(JobFair jobFair,ServletRequest request){
        HttpServletRequest req=(HttpServletRequest)request;
        String token=req.getHeader("token");
        String userJSON=(String) redisTemplate.opsForValue().get(token);
        return dwService.addJobFair(userJSON,jobFair);
    }
    @RequestMapping(value = "/dw/upJobFairStatus.action",method={RequestMethod.POST})
    public Integer upJobFairStatus(@RequestParam(value = "id")Integer id,@RequestParam(value = "status")Integer status){
        return dwService.updateJobFairStatus(id,status);
    }
    @RequestMapping(value = "/dw/getJobFairById.action",method={RequestMethod.POST})
    public JobFair getJobFairById(Integer id){
        return dwService.getJobFairById(id);
    }
    @RequestMapping(value = "/dw/upJobFair.action",method={RequestMethod.POST})
    public Integer upJobFair(JobFair jobFair,HttpServletRequest request){
        Integer id=Integer.parseInt(request.getHeader("id"));
        jobFair.setId(id);
        return dwService.upJobFair(jobFair);
    }
    @RequestMapping(value = "/dw/delJobFair.action",method={RequestMethod.POST})
    public Integer delJobFair(Integer id){
        return dwService.delJobFair(id);
    }
}
